package com.jlnk.stockdemo.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.jlnk.stockdemo.R;
import com.jlnk.stockdemo.bean.StockListResponse;

import java.util.List;

public class StockAdapter extends RecyclerView.Adapter<StockAdapter.StockViewHolder> {
    private List<StockListResponse.Data.Stock> stockItems;
    private OnItemClickListener onItemClickListener;

    public interface OnItemClickListener {
        void onItemClick(StockListResponse.Data.Stock stockItem);
    }

    public StockAdapter(List<StockListResponse.Data.Stock> stockItems) {
        this.stockItems = stockItems;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }

    @Override
    public StockViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_stock_list, parent, false);
        return new StockViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(StockViewHolder holder, int position) {
        StockListResponse.Data.Stock stockItem = stockItems.get(position);
        holder.tv_symbol.setText((String) stockItem.getSymbol());
        holder.tv_name.setText((String) stockItem.getName());
        holder.tv_area.setText((String) stockItem.getArea());
        holder.tv_industry.setText((String) stockItem.getIndustry());
        holder.tv_market.setText((String) stockItem.getMarket());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(stockItem);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return stockItems.size();
    }

    public static class StockViewHolder extends RecyclerView.ViewHolder {
        TextView tv_symbol;
        TextView tv_name;
        TextView tv_area;
        TextView tv_industry;
        TextView tv_market;

        public StockViewHolder(View itemView) {
            super(itemView);
            tv_symbol = itemView.findViewById(R.id.tv_symbol);
            tv_name = itemView.findViewById(R.id.tv_name);
            tv_area = itemView.findViewById(R.id.tv_area);
            tv_industry = itemView.findViewById(R.id.tv_industry);
            tv_market = itemView.findViewById(R.id.tv_market);
        }
    }
}
